import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/',
    redirect: '/home/products'
  },
  {
    path: '/home',
    component: () => import('@/views/Home.vue'),
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue')
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('@/views/Products.vue')
      },
      {
        path: 'hot-products',
        name: 'HotProducts',
        component: () => import('@/views/Products.vue'),
        props: { isHot: true }
      },
      {
        path: 'new-products',
        name: 'NewProducts',
        component: () => import('@/views/Products.vue'),
        props: { isNew: true }
      },
      {
        path: 'product/:id',
        name: 'ProductDetail',
        component: () => import('@/views/ProductDetail.vue'),
        props: true
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('@/views/Cart.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/views/Orders.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'orders/:id',
        name: 'OrderDetail',
        component: () => import('@/views/OrderDetail.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'favorites',
        name: 'Favorites',
        component: () => import('@/views/Favorites.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'categories',
        name: 'Categories',
        component: () => import('@/views/Categories.vue')
      },
      {
        path: 'flash-sale',
        name: 'FlashSale',
        component: () => import('@/views/Brands.vue')
      },
      {
        path: 'flash-sale-admin',
        name: 'FlashSaleAdmin',
        component: () => import('@/views/FlashSaleAdmin.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'flash-sale-monitor',
        name: 'FlashSaleMonitor',
        component: () => import('@/views/FlashSaleMonitor.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'addresses',
        name: 'Addresses',
        component: () => import('@/views/Addresses.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'help',
        name: 'Help',
        component: () => import('@/views/Help.vue')
      },
      {
        path: 'about',
        name: 'About',
        component: () => import('@/views/About.vue')
      },
      {
        path: 'checkout',
        name: 'Checkout',
        component: () => import('@/views/Checkout.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'search',
        name: 'Search',
        component: () => import('@/views/Search.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    // 始终滚动到顶部
    return { top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const isAuthenticated = !!token
  const isAdmin = userInfo.role === 'admin'

  // 检查是否需要登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
    return
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && !isAdmin) {
    next('/home')
    return
  }

  // 如果已登录还访问登录页，重定向到首页
  if (to.path === '/login' && isAuthenticated) {
    next('/home')
    return
  }

  next()
})

// 添加全局后置钩子，确保在每次导航后滚动到顶部
router.afterEach(() => {
  // 使用 nextTick 确保 DOM 更新后再滚动
  setTimeout(() => {
    // 尝试重置主内容区域的滚动位置
    const mainEl = document.querySelector('.el-main')
    if (mainEl) {
      mainEl.scrollTop = 0
    }
    // 同时也重置整个窗口的滚动位置
    window.scrollTo(0, 0)
  }, 100) // 添加小延迟确保 DOM 已完全更新
})

// 添加全局路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
})

// 添加导航守卫来处理重复导航
router.beforeEach((to, from, next) => {
  if (to.path === from.path && to.query === from.query) {
    next(false) // 阻止重复导航
  } else {
    next()
  }
})

export default router
